import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Carousel,
  Col,
  Form,
  InputNumber,
  Modal,
  Pagination,
  Popconfirm,
  Row,
  Table,
  Tabs,
  TabsProps,
  message,
} from 'antd';
import { useEffect, useState } from 'react';
import { getCommodity, getDrug, getMain, getMedicalServices,postOrder_commodity,postOrder_drug, postOrder_medicalServices } from '../Register/service';
import { history } from '@umijs/max';

const HomePage: React.FC = () => {
  const [commodity, setCommdity] = useState([]);
  const [main,setMain] = useState([])
  const [drug,setDrug] = useState([])
  const [isModalOpen,setIsModalOpen] = useState(false)
  const [form] = Form.useForm();
  const [commodityVal,setCommodityVal] = useState({})
  const [refreshCount,setRefreshCount] = useState(0)
  const [total,setTotal] = useState(0)
  const [mediclList,setMedicaList] = useState([])

  const fetchCommodity = async () => {
    const result = await getCommodity({
      pageNum:1
    });
    if (result.state === 200) {
      console.log(result);
      setCommdity(result?.data);
    }
  };
  const fetchMain = async () => {
    const result = await getMain()
    if(result.state === 200){
      setMain(result.data)
    }
  }
  const fetchMedicalServices = async () => {
    const result = await getMedicalServices()
    if(result.state === 200){
      console.log(result)
      setMedicaList(result.data)
    }
  }
  const fetchDrug = async () => {
    const result = await getDrug()
    if(result.state === 200){
      console.log(result)
      setDrug(result.data)
    }
  }

  const fetchOrder_commodity = async (params:any) => {
    const result = await postOrder_commodity({
      ...params
    })
    if(result.state === 200){
      message.success('购买成功')
    }
  }
  useEffect(() => {
    fetchCommodity();
    fetchMain()
    fetchMedicalServices()
    fetchDrug()
  }, [refreshCount]);

  const contentStyle: React.CSSProperties = {
    height: '360px',
    color: '#fff',
    lineHeight: '160px',
    textAlign: 'center',
    background: '#364d79',
  };

  const onChange = (key: string) => {
    console.log(key);
  };

  const dataSource = [
    {
      key: '1',
      name: '宠物清洗',
      age: 32,
      address: '1',
    },
    {
      key: '2',
      name: '宠物绝育',
      age: 42,
      address: '2',
    },
  ];

  const columns = [
    {
      title: '医疗服务信息',
      dataIndex: 'mtype',
      key: 'mtype',
    },
    {
      title: '今日服务数量',
      dataIndex: 'mstock',
      key: 'mstock',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <Popconfirm title="确认预定吗？" okText="确定" cancelText="考虑一下" onConfirm={async() => {
            const result = await postOrder_medicalServices({
              uid:window.localStorage.getItem('token'),
              mNum:1,
              m_stock:row?.mstock,
              mType:row?.mtype,
              mid:row?.mid
            })
            if(result.state === 200){
              message.success('预定成功')
              setRefreshCount(refreshCount + 1)
            }
          }}>
            <Button type="primary">预定</Button>
          </Popconfirm>
        );
      },
    },
  ];

  const dataSource2 = [
    {
      key: '1',
      name: '犬五联疫苗',
      age: 32,
      address: '1',
    },
    {
      key: '2',
      name: '猫三联疫苗',
      age: 42,
      address: '2',
    },
    {
      key: '3',
      name: '猫白血病疫苗',
      age: 42,
      address: '3',
    },
  ];

  const columns2 = [
    {
      title: '医疗用品信息',
      dataIndex: 'drugType',
      key: 'drugType',
    },
    {
      title: '库存数量',
      dataIndex: 'drugStock',
      key: 'drugStock',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <Popconfirm title="确认预定吗？" okText="确定" cancelText="考虑一下" onConfirm={async () => {
              const result = await postOrder_drug({
                uid:window.localStorage.getItem('token'),
                drugId:row?.drugId,
                drugStock:row?.drugStock,
                drug_num:1
              })
              if(result.state === 200){
                message.success('预定成功')
                setRefreshCount(refreshCount + 1)
              }
          }}>
            <Button type="primary">预定</Button>
          </Popconfirm>
        );
      },
    },
  ];


  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `商品`,
      children: (
        <div>
            <Row>
          {commodity?.map((x,idx) => {
            console.log(x)
            return (
              <Col span={6} key={idx}>
                <Card
                  style={{ width: 200 }}
                  cover={
                    <img
                      alt="example"
                      src={x?.picture && JSON.parse(x?.picture)}
                    />
                  }
                  actions={[
                    // <SettingOutlined key="setting" />,
                    <div key="stock">数量{x?.stock}</div>,
                    <div key="prise">¥{x?.price}</div>,
                    <div key="pay" onClick={() => {
                      setIsModalOpen(true)
                      setCommodityVal({stock:x?.stock,cid:x?.cid})
                    }}>立即购买</div>,
                    // <EditOutlined key="edit" />,
                  ]}
                >
                  {/* <Meta
      avatar={<Avatar src="https://xsgames.co/randomusers/avatar.php?g=pixel" />}
      title="Card title"
      description="This is the description"
    /> */}
                </Card>
              </Col>
            );
          })}
        </Row>
           <Pagination defaultCurrent={1} total={50} style={{position:'fixed',bottom:100,left:'50%',transform:'translate(-50%)'}}/>
        </div>
      
      ),
    },
    {
      key: '2',
      label: `医疗服务`,
      children: (
        <div>
          <Table dataSource={mediclList} columns={columns} />
        </div>
      ),
    },
    {
      key: '3',
      label: `医疗用品`,
      children: <Table dataSource={drug} columns={columns2} />,
    },
  ];

  useEffect(() => {
    if(!window.localStorage.getItem('token') || !window.localStorage.getItem('info')){
      history.push('/login')
    }
  },[])

  return (
    <PageContainer ghost>
      <div>
        <Carousel
          effect="fade"
          autoplay
          style={{ width: '40%', margin: '0 auto' }}
        >{
          main?.map((x,idx) => {
            return(
              <div key={idx}>
              <h3 style={contentStyle}>
               <img
                  style={{ width: '100%', height: '100%' }}
                  src={JSON.parse(x?.picture)}
                  onClick={() => {
                    window.open(x?.url)
                  }}
                />
              </h3>
            </div>
            )
          })
        }
        </Carousel>
      </div>
      <div>
        <Tabs
          defaultActiveKey="1"
          type="card"
          items={items}
          onChange={onChange}
        />
      </div>
      <Modal title="预定" open={isModalOpen} onOk={async () => {
        const params = form.getFieldsValue();
        if(params){
          fetchOrder_commodity({
            ...params,
            uid:window.localStorage.getItem('token'),
            ...commodityVal
          })
          setIsModalOpen(false)
        }
        form.submit()
      }}  onCancel={() => {
        setIsModalOpen(false)
        
      }}>
         <Form
      name="basic"
      form={form}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      initialValues={{ remember: true }}
      autoComplete="off"
    >
      <Form.Item
        label="数量"
        name="c_num"
        rules={[{ required: true, message: '请输入数量' }]}
      >
        <InputNumber placeholder='请输入数量'/>
      </Form.Item>

    </Form>
      </Modal>
    </PageContainer>
  );
};

export default HomePage;
